﻿using System;
using System.ComponentModel.Composition;
using SS.Common.Logging;

namespace SS.Common.Utilities
{
    [Export(typeof(MailHelper))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class MailHelper
    {
        /// <summary>
        /// The logger instance
        /// </summary>
        public static readonly ILogger Logger = LoggerManager.GetLogger(typeof(MailHelper).Name);

        /// <summary>
        /// The method for sending email 
        /// </summary>
        /// <param name="mailServer">The mail server</param>
        /// <param name="subject">The subject of email</param>
        /// <param name="content">The content of email</param>
        /// <param name="to">The destination address will be received email</param>
        /// <param name="from">The source address</param>
        /// <param name="password">The password of source address</param>
        /// <param name="supportSSL"></param>
        public bool SendMail(string mailServer, string subject, string content, string to, string from, string password, bool supportSSL = false)
        {
            Logger.Info("SendMail --> Start");
            Logger.InfoFormat("mailServer: {0}", mailServer);
            Logger.InfoFormat("from: {0}", from);
            Logger.InfoFormat("to: {0}", to);

            var result = true;
            try
            {
                var mailclient = new System.Net.Mail.SmtpClient
                {
                    Host = mailServer,
                    EnableSsl = supportSSL,
                    UseDefaultCredentials = true,
                    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                    Credentials = new System.Net.NetworkCredential(from, password)
                };

                var mm = new System.Net.Mail.MailMessage(from, to)
                {
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = content,
                    Priority = System.Net.Mail.MailPriority.High
                };

                mailclient.Send(mm);
            }
            catch (Exception ex)
            {
                result = false;
                Logger.ErrorFormat("SendMail: {0}", ex.ToString());
            }

            Logger.InfoFormat("result: {0}", result);
            Logger.Info("SendMail <-- End");
            return result;
        }
    }
}